package com.ruoyi.ucar.controller;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ucar.boreq.*;
import com.ruoyi.ucar.boresp.*;
import com.ruoyi.ucar.common.CommonVoResp;
import com.ruoyi.ucar.common.ResultEnum;
import com.ruoyi.ucar.service.ITCustomerService;
import com.ruoyi.ucar.domain.TCustomer;
import com.ruoyi.ucar.util.CommonUtil;
import com.ruoyi.ucar.util.ResponseUtil;
import com.ruoyi.ucar.util.WXQrCodeUtil;
import com.ruoyi.ucar.voreq.*;
import com.ruoyi.ucar.voresp.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
 
/**
 * 客户主Controller
 * 
 * @author sungangbin
 * @date 2025-05-13
 */
@Api(value = "客户管理",tags = "客户管理模块接口")
@RestController
@RequestMapping("/ucar/customer")
public class TCustomerController extends BaseController
{

    @Value("${ucar.wx.miniapp.appid}")
    private String appId;

    @Value("${ucar.wx.miniapp.secret}")
    private String secret;



    @Autowired
    private ITCustomerService tCustomerService;


    @ApiOperation("生成代理商分享二维码")
    @PostMapping("/agentQrCode")
    public CommonVoResp<AgentQrCodeVoResp> agentQrCode(@RequestBody AgentQrCodeVoReq agentQrCodeVoReq){
        CommonVoResp<AgentQrCodeVoResp> commonVoResp=new CommonVoResp<>();
        logger.info("生成代理商分享二维码VO端入口参数:{}",agentQrCodeVoReq);
        String token = null;
        AgentQrCodeVoResp agentQrCodeVoResp=null;
        try {
            token = WXQrCodeUtil.postToken(appId, secret);
            String qrCode=  WXQrCodeUtil.generateQrCode( "pages/login/index", "customerId="+agentQrCodeVoReq.getCustomerId(), token);
            agentQrCodeVoResp=new AgentQrCodeVoResp();
            agentQrCodeVoResp.setAgentQrCode(qrCode);
        } catch (Exception e) {
            logger.error("生成代理商分享二维码异常信息:{}",e.getMessage());
            return CommonUtil.setCommonVoRespNoDataError(commonVoResp);
        }
        commonVoResp.setData(agentQrCodeVoResp);
        return commonVoResp;
    }


    @ApiOperation("收支查询-mobile使用")
    @PostMapping("/income")
    public CommonVoResp<List<InComeTotolVoResp>> income(@RequestBody InComeTotolVoReq inComeTotolVoReq){
        CommonVoResp<List<InComeTotolVoResp>> commonVoResp=new CommonVoResp<>();
        logger.info("客户列表查询VO端入口参数:{}",inComeTotolVoReq);
        List<InComeTotolVoResp> inComeTotolVoResps=new ArrayList<>();
        List<InComeTotolBoResp> inComeTotolBoResps= tCustomerService.income(CommonUtil.objToObj(inComeTotolVoReq,InComeTotolBoReq.class));
        inComeTotolBoResps=Optional.ofNullable(inComeTotolBoResps)
                .orElseGet(Collections::emptyList)
                .stream()
                .sorted(
                        Comparator.nullsLast(
                                Comparator.comparing(
                                        obj -> Optional.ofNullable(obj)
                                                .map(InComeTotolBoResp::getDate)
                                                .orElse(null),
                                        Comparator.nullsLast(Comparator.reverseOrder())
                                )
                        )
                )
                .collect(Collectors.toList());
        inComeTotolBoResps.forEach(inComeTotolBoResp -> {
            InComeTotolVoResp inComeTotolVoResp=CommonUtil.objToObj(inComeTotolBoResp,InComeTotolVoResp.class);
            inComeTotolVoResps.add(inComeTotolVoResp);
        });
        commonVoResp.setData(inComeTotolVoResps);
        return commonVoResp;
    }


    /**
     * 查询客户主列表
     */
    @ApiOperation("客户列表查询-分页功能")
    @PostMapping("/list")
    public CommonVoResp<CustomerListQueryVoResp> list(@RequestBody CustomerListQueryVoReq customerListQueryVoReq)
    {
        CommonVoResp<CustomerListQueryVoResp> commonVoResp=new CommonVoResp<>();
        logger.info("客户列表查询VO端入口参数:{}",customerListQueryVoReq);
         if(
                 customerListQueryVoReq.getPageIndex()==null||
                         customerListQueryVoReq.getPageSize()==null){
            return CommonUtil.setCommonVoRespNoParam(commonVoResp);
        }
        CustomerListQueryBoReq customerListQueryBoReq=CommonUtil.objToObj(customerListQueryVoReq,CustomerListQueryBoReq.class);
        customerListQueryBoReq.setPageIndex(customerListQueryVoReq.getPageIndex());
        customerListQueryBoReq.setPageSize(customerListQueryVoReq.getPageSize());
        CustomerListQueryBoResp customerListQueryBoResp= tCustomerService.queryCustomerByCond(customerListQueryBoReq);
        if(StringUtils.isNotNull(customerListQueryBoResp)){
            CustomerListQueryVoResp customerListQueryVoResp=new CustomerListQueryVoResp();
            List<CustomerListQueryVo> customerListQueryVos=new ArrayList<>();
            customerListQueryVoResp.setTotalCount(customerListQueryBoResp.getTotalCount());
            customerListQueryVoResp.setTotalPage(customerListQueryBoResp.getTotalPage());
            customerListQueryBoResp.getCustomerListQueryBos().forEach(customerListQueryBo -> {
                CustomerListQueryVo customerListQueryVo=CommonUtil.objToObj(customerListQueryBo,CustomerListQueryVo.class);
                customerListQueryVos.add(customerListQueryVo);
            });
            customerListQueryVoResp.setCustomerListQueryVos(customerListQueryVos);
            commonVoResp.setData(customerListQueryVoResp);
        }else{
            return CommonUtil.setCommonVoRespNoDataError(commonVoResp);
        }
        logger.info("客户列表查询-VO端出参:{}",commonVoResp);
        return commonVoResp;
    }


    /**
     * 查询客户主列表
     */
    @ApiOperation("客户列表查询-没有分页功能")
    @PostMapping("/listNoPage")
    public CommonVoResp<CustomerListQueryNoPageVoResp> listNoPage(@RequestBody CustomerListQueryNoPageVoReq customerListQueryNoPageVoReq)
    {
        CommonVoResp<CustomerListQueryNoPageVoResp> commonVoResp=new CommonVoResp<>();
        logger.info("客户列表查询-没有分页VO端入口参数:{}",customerListQueryNoPageVoReq);
        CustomerListQueryNoPageBoReq customerListQueryNoPageBoReq=CommonUtil.objToObj(customerListQueryNoPageVoReq, CustomerListQueryNoPageBoReq.class);
        CustomerListQueryNoPageBoResp customerListQueryNoPageBoResp= tCustomerService.queryCustomerNoPageByCond(customerListQueryNoPageBoReq);
        if(StringUtils.isNotNull(customerListQueryNoPageBoResp)){
            CustomerListQueryNoPageVoResp customerListQueryNoPageVoResp=new CustomerListQueryNoPageVoResp();
            List<CustomerListQueryNoPageVo> customerListQueryNoPageVos=new ArrayList<>();
            customerListQueryNoPageBoResp.getCustomerListQueryNoPageBos().forEach(customerListQueryNoPageBo -> {
                CustomerListQueryNoPageVo customerListQueryNoPageVo=CommonUtil.objToObj(customerListQueryNoPageBo,CustomerListQueryNoPageVo.class);
                customerListQueryNoPageVos.add(customerListQueryNoPageVo);
            });
            customerListQueryNoPageVoResp.setCustomerListQueryNoPageVos(customerListQueryNoPageVos);
            commonVoResp.setData(customerListQueryNoPageVoResp);
        }else{
            if(StringUtils.isNotEmpty(customerListQueryNoPageVoReq.getAgentGrade())){
                return commonVoResp;
            }
            return CommonUtil.setCommonVoRespNoDataError(commonVoResp);
        }
        logger.info("客户列表查询--没有分页功能-VO端出参:{}",commonVoResp);
        return commonVoResp;
    }

    /**
     * 导出客户主列表
     */
    @PreAuthorize("@ss.hasPermi('ucar:customer:export')")
    @Log(title = "客户主", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TCustomer tCustomer)
    {
        List<TCustomer> list = tCustomerService.selectTCustomerList(tCustomer);
        ExcelUtil<TCustomer> util = new ExcelUtil<TCustomer>(TCustomer.class);
        util.exportExcel(response, list, "客户主数据");
    }

    /**
     * 获取客户详细信息
     */
    @ApiOperation("获取客户详细信息接口-id和customerUuid，两者传一即可")
    @PostMapping(value = "/detail")
    public CommonVoResp<CustomerDetailQueryVoResp> productDetailQuery(@RequestBody CustomerDetailQueryVoReq customerDetailQueryVoReq)
    {
        CommonVoResp<CustomerDetailQueryVoResp> commonVoResp=new CommonVoResp<>();
        logger.info("获取客户详细信息入参：{}",customerDetailQueryVoReq);
        if(
                customerDetailQueryVoReq.getCustomerUuid()==null&&
                        customerDetailQueryVoReq.getId()==null){
            return CommonUtil.setCommonVoRespNoParam(commonVoResp);
        }
        CustomerDetailQueryBoResp  customerDetailQueryBoResp=tCustomerService.customerDetailQuery(CommonUtil.objToObj(customerDetailQueryVoReq, CustomerDetailQueryBoReq.class));
        if(StringUtils.isNull(customerDetailQueryBoResp)){
            return CommonUtil.setCommonVoRespNoDataError(commonVoResp);
        }else{
            CustomerDetailQueryVoResp customerDetailQueryVoResp=CommonUtil.objToObj(customerDetailQueryBoResp,CustomerDetailQueryVoResp.class);
            commonVoResp.setData(customerDetailQueryVoResp);
        }
        logger.info("获取客户详细信息出参：{}",commonVoResp);
        return commonVoResp;
    }
    /**
     * 新增客户主
     */
    @ApiOperation("新增客户接口")
    @PostMapping("/add")
    public CommonVoResp<CustomerAddVoResp> add(@RequestBody CustomerAddVoReq customerAddVoReq)
    {
             CommonVoResp<CustomerAddVoResp> commonVoResp=new CommonVoResp<>();
             logger.info("新增客户入参：{}",customerAddVoReq);
             CustomerAddVoResp customerAddVoResp=new CustomerAddVoResp();
             String customerUuid = tCustomerService.saveCustomer(customerAddVoReq);
             customerAddVoResp.setCustomerUuid(customerUuid);
             commonVoResp.setData(customerAddVoResp);
             logger.info("新增客户出参：{}",commonVoResp);
             return commonVoResp;
    }

    /**
     * 修改客户
     */
    @ApiOperation("修改客户接口")
    @PostMapping("/udpate")
    public CommonVoResp<String> udpate(@RequestBody CustomerUpdateVoReq customerUpdateVoReq)
    {
        CommonVoResp<String> commonVoResp=new CommonVoResp<>();
        logger.info("修改客户入参：{}",customerUpdateVoReq);
        int updateNumber=tCustomerService.updateCustomer(customerUpdateVoReq);
        if(updateNumber==8){
            commonVoResp.setCode(500);
            commonVoResp.setMessage("该手机号码已经被他人使用，不允许修改！");
            return commonVoResp;
        }
        return ResponseUtil.commonUpdateResult(updateNumber,commonVoResp);
    }


    /**
     * 头像和昵称
     */
    @ApiOperation("上传客户相关信息-头像和昵称接口")
    @PostMapping("/uploadCustomerData")
    public CommonVoResp<String> uploadCustomerData(CustomerUploadDataVoReq customerUploadDataVoReq)
    {
        CommonVoResp<String> commonVoResp=new CommonVoResp<>();
        logger.info("上传客户相关信息-头像和昵称入参：{}",customerUploadDataVoReq);
        if(
                customerUploadDataVoReq.getAvatarFile()==null&&
                        StringUtils.isEmpty(customerUploadDataVoReq.getNickName())){
            return CommonUtil.setCommonVoRespNoParam(commonVoResp);
        }
        return ResponseUtil.commonUpdateResult(tCustomerService.uploadCustomerData(CommonUtil.objToObj(customerUploadDataVoReq,CustomerUploadDataBoReq.class)),commonVoResp);
    }

    /**
     * 删除客户
     */
    @ApiOperation("删除客户接口-id和customerUuid，两者传一即可")
    @PostMapping("/delete")
    public CommonVoResp<String> delete(@RequestBody DeleteCustomerVoReq  deleteCustomerVoReq)
    {
        CommonVoResp<String> commonVoResp=new CommonVoResp<>();
        if(
                deleteCustomerVoReq.getCustomerUuid()==null&&
                        deleteCustomerVoReq.getId()==null){
            return CommonUtil.setCommonVoRespNoParam(commonVoResp);
        }
        logger.info("删除客户入参：{}",deleteCustomerVoReq);
        return ResponseUtil.commonDeleteResult(tCustomerService.deleteTCustomerById(deleteCustomerVoReq.getCustomerUuid(),deleteCustomerVoReq.getId()),commonVoResp);
    }

    /**
     * 批量删除客户
     */
    @ApiOperation("批量删除客户接口-ids和customerUuids，两者传一即可")
    @PreAuthorize("@ss.hasPermi('ucar:image:remove')")
    @PostMapping("/batchDelete")
    public CommonVoResp<String>  batchDelete(@RequestBody BatchDeleteCustomerVoReq  batchDeleteCustomerVoReq)
    {
        CommonVoResp<String> commonVoResp=new CommonVoResp<>();
        if((StringUtils.isNull(batchDeleteCustomerVoReq.getCustomerUuids())||batchDeleteCustomerVoReq.getCustomerUuids().length==0)
                &&(StringUtils.isNull(batchDeleteCustomerVoReq.getIds())||batchDeleteCustomerVoReq.getIds().length==0)){
            return CommonUtil.setCommonVoRespNoParam(commonVoResp);
        }
        logger.info("批量删除客户入参：{}",batchDeleteCustomerVoReq);
        return ResponseUtil.commonDeleteResult(tCustomerService.batchDelete(batchDeleteCustomerVoReq.getCustomerUuids(),batchDeleteCustomerVoReq.getIds()),commonVoResp);
    }

    @ApiOperation("代理商转余额接口")
    @PostMapping("/transferBalance")
    public CommonVoResp<String> transferBalance(@RequestBody ProxyTransferBalanceVoReq proxyTransferBalanceVoReq)
    {
        CommonVoResp<String> commonVoResp=new CommonVoResp<>();
        if(StringUtils.isNull(proxyTransferBalanceVoReq.getTotalFeel())
        ){
            commonVoResp = CommonUtil.setCommonVoRespNoParam(commonVoResp);
            logger.info("代理商转余额接口出参:{}",commonVoResp);
            return commonVoResp;
        }
        logger.info("代理商转余额接口VO端入参:{}",proxyTransferBalanceVoReq);
        TCustomer tCustomer= tCustomerService.getBaseMapper().selectOne(new LambdaQueryWrapper<TCustomer>()
                .eq(TCustomer::getSysUserId, SecurityUtils.getLoginUser()
                        .getUserId()).eq(TCustomer::getDeleteFlag,1L));

        if(proxyTransferBalanceVoReq.getTotalFeel().compareTo(tCustomer.getTotalAgencyFee())>0){
            commonVoResp.setCode(ResultEnum.CUSTOMERTBNOTENOUGH.getCode());
            commonVoResp.setMessage(ResultEnum.CUSTOMERTBNOTENOUGH.getMsg());
            logger.info("代理商转余额接口出参:{}",commonVoResp);
            return  commonVoResp;
        }else{
            tCustomer.setBalanceNumber(tCustomer.getBalanceNumber().add(proxyTransferBalanceVoReq.getTotalFeel()));
            tCustomer.setTotalAgencyFee(tCustomer.getTotalAgencyFee().subtract(proxyTransferBalanceVoReq.getTotalFeel()));
            tCustomerService.getBaseMapper().updateById(tCustomer);
        }
        logger.info("代理商转余额接口出参:{}",commonVoResp);
        return  commonVoResp;
    }



    @ApiOperation("用户的余额和赠送金额消费接口")
    @PostMapping("/balanceConsume")
    public CommonVoResp<CustomerBalanceConsumeVoResp> balanceConsume(@RequestBody CustomerBalanceConsumeVoReq customerBalanceConsumeVoReq)
    {
        CommonVoResp<CustomerBalanceConsumeVoResp> commonVoResp=new CommonVoResp<>();
        if(StringUtils.isEmpty(customerBalanceConsumeVoReq.getOrderCode())
        ){
            commonVoResp = CommonUtil.setCommonVoRespNoParam(commonVoResp);
            return commonVoResp;
        }
        logger.info("用户的余额和赠送金额消费接口VO端入参:{}",customerBalanceConsumeVoReq);
        CustomerBalanceConsumeBoReq customerBalanceConsumeBoReq= CommonUtil.objToObj(customerBalanceConsumeVoReq,  CustomerBalanceConsumeBoReq.class);
        logger.info("用户的余额和赠送金额消费VO端转BO端入参:{}",customerBalanceConsumeBoReq);
        CustomerBalanceConsumeBoResp customerBalanceConsumeBoResp=tCustomerService.balanceConsume(customerBalanceConsumeBoReq);
        CustomerBalanceConsumeVoResp customerBalanceConsumeVoResp=CommonUtil.objToObj(customerBalanceConsumeBoResp,CustomerBalanceConsumeVoResp.class);
        commonVoResp.setData(customerBalanceConsumeVoResp);
        if(customerBalanceConsumeVoResp.getConsumeCode()!=ResultEnum.SUCCESS.getCode()){
            commonVoResp.setCode(customerBalanceConsumeVoResp.getConsumeCode());
            commonVoResp.setMessage(customerBalanceConsumeVoResp.getConsumeMessage());
        }
        logger.info("用户的余额和赠送金额消费出参:{}",commonVoResp);
        return  commonVoResp;
    }

    @ApiOperation("用户的余额和赠送金额退单还原接口")
    @PostMapping("/balanceRestore")
    public CommonVoResp<CustomerBalanceRestoreVoResp> balanceRestore(@RequestBody CustomerBalanceRestoreVoReq customerBalanceRestoreVoReq)
    {
        CommonVoResp<CustomerBalanceRestoreVoResp> commonVoResp=new CommonVoResp<>();
        if(StringUtils.isEmpty(customerBalanceRestoreVoReq.getOrderCode())
        ){
            commonVoResp = CommonUtil.setCommonVoRespNoParam(commonVoResp);
            return commonVoResp;
        }
        logger.info("用户的余额和赠送金额退单还原接口VO端入参:{}",customerBalanceRestoreVoReq);
        CustomerBalanceRestoreBoReq customerBalanceRestoreBoReq= CommonUtil.objToObj(customerBalanceRestoreVoReq,  CustomerBalanceRestoreBoReq.class);
        logger.info("用户的余额和赠送金额退单还原VO端转BO端入参:{}",customerBalanceRestoreBoReq);
        CustomerBalanceRestoreBoResp customerBalanceRestoreBoResp=tCustomerService.balanceRestore(customerBalanceRestoreBoReq);
        CustomerBalanceRestoreVoResp customerBalanceRestoreVoResp=CommonUtil.objToObj(customerBalanceRestoreBoResp,CustomerBalanceRestoreVoResp.class);
        commonVoResp.setData(customerBalanceRestoreVoResp);
        if(customerBalanceRestoreVoResp.getRestoreCode()!=ResultEnum.SUCCESS.getCode()){
            commonVoResp.setCode(customerBalanceRestoreVoResp.getRestoreCode());
            commonVoResp.setMessage(customerBalanceRestoreVoResp.getRestoreMessage());
        }
        logger.info("用户的余额和赠送金额退单还原出参:{}",commonVoResp);
        return  commonVoResp;
    }



    /**
     * 获取客户详细信息
     */
    @ApiOperation("获取当前登录客户详细信息接口-mobile使用")
    @PostMapping(value = "/mobileDetail")
    public CommonVoResp<CustomerDetailMobileQueryVoResp> productDetailMobileQuery()
    {
        CommonVoResp<CustomerDetailMobileQueryVoResp> commonVoResp=new CommonVoResp<>();
        CustomerDetailMobileQueryBoResp  customerDetailMobileQueryBoResp=tCustomerService.customerDetailMobileQuery( );
        if(StringUtils.isNull(customerDetailMobileQueryBoResp)){
            return CommonUtil.setCommonVoRespNoDataError(commonVoResp);
        }else{
            CustomerDetailMobileQueryVoResp  customerDetailMobileQueryVoResp=CommonUtil.objToObj(customerDetailMobileQueryBoResp,CustomerDetailMobileQueryVoResp.class);
            commonVoResp.setData(customerDetailMobileQueryVoResp);
        }
        logger.info("获取当前登录客户详细信息接口-mobile使用出参：{}",commonVoResp);
        return commonVoResp;
    }

    /**
     * 上传当前登录客户的签名
     */
    @ApiOperation("上传当前登录客户的签名图片接口-mobile使用")
    @PostMapping(value = "/uploadCustomerSign")
    public CommonVoResp<CustomerSignVoResq> uploadCustomerSign(UploadCustomerSignVoReq uploadCustomerSignVoReq)
    {
        CommonVoResp<CustomerSignVoResq> commonVoResp=new CommonVoResp<>();
        if(StringUtils.isNull(uploadCustomerSignVoReq.getFile())){
            return CommonUtil.setCommonVoRespNoSignParam(commonVoResp);
        }
        CustomerSignBoResq customerSignBoResq= tCustomerService.judgeCustomerSign();
        if(StringUtils.isNull(customerSignBoResq)){
            commonVoResp.setCode(ResultEnum.CUSTOMERNODATA.getCode());
            commonVoResp.setMessage(ResultEnum.CUSTOMERNODATA.getMsg());
        }else{
//            if(!customerSignBoResq.getSignFlag()){
                try {
                    String   signFileMainUuid= tCustomerService.uploadCustomerSign(CommonUtil.objToObj(uploadCustomerSignVoReq,UploadCustomerSignBoReq.class));
                    CustomerSignVoResq customerSignVoResq=new CustomerSignVoResq();
                    customerSignVoResq.setSignFlag(new Boolean(true));
                    customerSignVoResq.setSignFileMainUuid(signFileMainUuid);
                    commonVoResp.setData(customerSignVoResq);
                } catch (IOException e) {
                    commonVoResp.setCode(ResultEnum.CUSTOMERSIGNFAIL.getCode());
                    commonVoResp.setMessage(ResultEnum.CUSTOMERSIGNFAIL.getMsg());
                }
//            }else{
//                CustomerSignVoResq customerSignVoResq=CommonUtil.objToObj(customerSignBoResq,CustomerSignVoResq.class);
//                commonVoResp.setData(customerSignVoResq);
//            }
        }
        logger.info("上传当前登录客户的签名接口-mobile使用出参：{}",commonVoResp);
        return commonVoResp;
    }



}
